import { z } from "zod";
import { createTRPCRouter, protectedProcedure } from "../trpc";
import { TRPCError } from "@trpc/server";

export const taskContentRouter = createTRPCRouter({
  create: protectedProcedure
    .input(z.object({
      taskId: z.string(),
      courseId: z.string(),
      title: z.string(),
      content: z.string(),
    }))
    .mutation(async ({ ctx, input }) => {
      // 验证任务是否存在
      const task = await ctx.db.task.findUnique({
        where: { id: input.taskId },
        include: { course: true },
      });

      if (!task) {
        throw new TRPCError({
          code: "NOT_FOUND",
          message: "任务不存在",
        });
      }

      // 验证权限
      if (task.course.teacherId !== ctx.session.user.id) {
        throw new TRPCError({
          code: "FORBIDDEN",
          message: "没有权限创建内容",
        });
      }

      return ctx.db.taskContent.create({
        data: input,
      });
    }),

  update: protectedProcedure
    .input(z.object({
      id: z.string(),
      title: z.string(),
      content: z.string(),
    }))
    .mutation(async ({ ctx, input }) => {
      const { id, ...data } = input;

      const existingContent = await ctx.db.taskContent.findUnique({
        where: { id },
        include: { course: true },
      });

      if (!existingContent) {
        throw new TRPCError({
          code: "NOT_FOUND",
          message: "内容不存在",
        });
      }

      if (existingContent.course.teacherId !== ctx.session.user.id) {
        throw new TRPCError({
          code: "FORBIDDEN",
          message: "没有权限修改内容",
        });
      }

      return ctx.db.taskContent.update({
        where: { id },
        data,
      });
    }),
}); 